<?php

namespace App\Jobs;

use Illuminate\Bus\Queueable;
use Illuminate\Queue\SerializesModels;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use App\Models\MeetingUser;
use App\Handlers\Face;
use App\Handlers\Oss;

class MeetingUserNewPerson implements ShouldQueue
{
    use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;

    protected $meetingUser;

    /**
     * Create a new job instance.
     *
     * @return void
     */
    public function __construct(MeetingUser $meetingUser)
    {
        $this->meetingUser = $meetingUser;
    }

    /**
     * Execute the job.
     *
     * @return void
     */
    public function handle()
    {
        $person = $this->newPerson($this->meetingUser);

        $update_data['person_id'] = $person['person_id'];
        $update_data['person_session_id'] = $person['session_id'];
        $update_data['person_face_id'] = $person['face_id'];

        MeetingUser::where('id', $this->meetingUser->id)->update($update_data);
    }

    /**
     * 腾讯优图新建用户
     * @param $user_info
     * @return bool|\TencentYoutuyun\返回的结果，JSON字符串，字段参见API文档
     */
    private function newPerson($user_info)
    {
        $url = Oss::getPublicObjectURL($user_info->face_image);
        $person_id = "person".$user_info->id;
        $group_ids = [(string)$user_info->meeting_id];
        $person_name = $user_info->real_name;
        $person_tag = $user_info->tag;

        $face = new Face($person_id);

        try {
            $ret = $face->newPersonUrl($url, $person_id, $group_ids, $person_name, $person_tag);
            if ($ret['errorcode'] != 0) {
                return false;
            }
        } catch (\Exception $e) {
            return false;
        }

        return $ret;
    }
}
